package com.itlong.cloud.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.utils.encrypt.DesEncryptUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;


/**
 * <desc>
 *     主数据源配置
 * </desc>
 *
 * @createDate 2019/07/17
 */
@Configuration
// 扫描 Mapper 接口并容器管理,注：新增dao，需要关注此处，否则dao层可能会注入失败
@MapperScan(basePackages = {"com.itlong.cloud.*.dao"},
        sqlSessionFactoryRef = "masterSqlSessionFactory")
public class DataSourceConfig {
 
    // 精确到 master 目录，以便跟其他数据源隔离
    //static final String PACKAGE = "com.itlong.cloud.app.dao,com.itlong.cloud.operate.dao,com.itlong.cloud.property.dao";
    static final String MAPPER_LOCATION = "classpath*:mapper/*/*.xml";

    @Value("${" + PlatformConstants.DATASOURCE_MYSQL_URL + "}")
    private String url;

    @Value("${" + PlatformConstants.DATASOURCE_MYSQL_USERNAME + "}")
    private String user;

    @Value("${" + PlatformConstants.DATASOURCE_MYSQL_PASSWORD + "}")
    private String password;

    @Value("com.mysql.jdbc.Driver")
    private String driverClass;

    //默认为主数据源
    @Bean(name = "masterDataSource")
    @Primary
    public DataSource masterDataSource() {
        try {
            user = DesEncryptUtil.aesDecrypt(user, url.substring(0, 16));
            password = DesEncryptUtil.aesDecrypt(password, url.substring(0, 16));
            if (StringUtils.isEmpty(user) || StringUtils.isEmpty(password)) {
                throw new NullPointerException("解密数据库信息为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(user.substring(0,user.length()-16));
        dataSource.setPassword(password.substring(0,password.length()-16));
        return dataSource;
    }
 
    @Bean(name = "masterTransactionManager")
    @Primary
    public DataSourceTransactionManager masterTransactionManager() {
        return new DataSourceTransactionManager(masterDataSource());
    }
 
    @Bean(name = "masterSqlSessionFactory")
    @Primary
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(masterDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(DataSourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
}